/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.semodbus.server.msg;

import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.msg.ModbusRequest;
import com.ghgande.j2mod.modbus.msg.ModbusResponse;
import com.ghgande.j2mod.modbus.msg.WriteSingleRegisterResponse;
import com.ghgande.j2mod.modbus.net.AbstractModbusListener;
import com.ghgande.j2mod.modbus.procimg.IllegalAddressException;
import com.ghgande.j2mod.modbus.procimg.ProcessImage;
import com.ghgande.j2mod.modbus.procimg.Register;
import com.ghgande.j2mod.modbus.procimg.SimpleRegister;
import com.seari.semodbus.bean.PLCDevice;
import com.seari.semodbus.bean.VirtualModbus;
import com.seari.semodbus.utils.ModbusUtil;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Rainbow
 */
public class SEWriteSingleRegisterRequest extends ModbusRequest
{
    protected static Logger logger = LoggerFactory.getLogger(SEWriteSingleRegisterRequest.class);
    // instance attributes
    private int reference;
    private Register register;

    public SEWriteSingleRegisterRequest()
    {
        super();
        setFunctionCode(Modbus.WRITE_SINGLE_REGISTER);
        setDataLength(4);
    }
    
    public ModbusResponse getResponse() {
        WriteSingleRegisterResponse response = new WriteSingleRegisterResponse();

        response.setHeadless(isHeadless());
        if (!isHeadless()) {
            response.setProtocolID(getProtocolID());
            response.setTransactionID(getTransactionID());
        }
        response.setFunctionCode(getFunctionCode());
        response.setUnitID(getUnitID());

        return response;
    }
    
    /**
     * Constructs a new <tt>WriteSingleRegisterRequest</tt> instance with a
     * given reference and value to be written.
     *
     * @param ref the reference number of the register to read from.
     * @param reg the register containing the data to be written.
     */
    public SEWriteSingleRegisterRequest(int ref, Register reg) {
        super();

        setFunctionCode(Modbus.WRITE_SINGLE_REGISTER);
        setDataLength(4);

        reference = ref;
        register = reg;
    }
    

    
    @Override
    public ModbusResponse createResponse(AbstractModbusListener listener) {
        SEWriteSingleRegisterResponse response;
        Register reg;

        // 1. get process image
        ProcessImage procimg = listener.getProcessImage(getUnitID());
        // 2. get register
        try {
            reg = procimg.getRegister(reference);
            // 3. set Register
            reg.setValue(register.toBytes());
            int pos = VirtualModbus.calPosToKey(reference);
            PLCDevice device = VirtualModbus.devHashMap.get(pos);
            int realPos = VirtualModbus.getRealPos(device, reference);
            ModbusUtil.writeRegister(device.getIp(), device.getPort(), device.getSlaveID(),realPos, reg.getValue());
        }
        catch (IllegalAddressException iaex) {
            return createExceptionResponse(Modbus.ILLEGAL_ADDRESS_EXCEPTION);
        }
        response = new SEWriteSingleRegisterResponse(this.getReference(), reg.getValue());
        // transfer header data
        if (!isHeadless()) {
            response.setTransactionID(this.getTransactionID());
            response.setProtocolID(this.getProtocolID());
        }
        else {
            response.setHeadless();
        }
        response.setUnitID(this.getUnitID());
        response.setFunctionCode(this.getFunctionCode());

        return response;
    }

    /**
     * Returns the reference of the register to be written to with this
     * <tt>WriteSingleRegisterRequest</tt>.
     *
     * @return the reference of the register to be written to.
     */
    public int getReference() {
        return reference;
    }

    /**
     * Sets the reference of the register to be written to with this
     * <tt>WriteSingleRegisterRequest</tt>.
     *
     * @param ref the reference of the register to be written to.
     */
    public void setReference(int ref) {
        reference = ref;
    }

    /**
     * Returns the register to be written with this
     * <tt>WriteSingleRegisterRequest</tt>.
     *
     * @return the value to be written to the register.
     */
    public Register getRegister() {
        return register;
    }

    /**
     * Sets the value that should be written to the register with this
     * <tt>WriteSingleRegisterRequest</tt>.
     *
     * @param reg the register to be written.
     */
    public void setRegister(Register reg) {
        register = reg;
    }

    @Override
    public void writeData(DataOutput dout) throws IOException {
        dout.writeShort(reference);
        dout.write(register.toBytes());
    }

    @Override
    public void readData(DataInput din) throws IOException {
        reference = din.readUnsignedShort();
        register = new SimpleRegister(din.readByte(), din.readByte());
    }

    @Override
    public byte[] getMessage() {
        byte result[] = new byte[4];

        result[0] = (byte)((reference >> 8) & 0xff);
        result[1] = (byte)(reference & 0xff);
        result[2] = (byte)((register.getValue() >> 8) & 0xff);
        result[3] = (byte)(register.getValue() & 0xff);

        return result;
    }
    
}
